package com.example.demo.practice;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;

import com.example.demo.practice.innerclass.DownApkServer;
import com.example.demo.practice.innerclass.IBaseActivity;
import com.example.demo.practice.tool.ServerHttp;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class SettingActivity extends IBaseActivity {
    private ServerHttp serverHttp;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            JSONArray jsonArray = serverHttp.getData();
            String versionName = "";
            try {
                // ---get the package info---
                PackageManager pm = SettingActivity.this.getPackageManager();
                PackageInfo pi = pm.getPackageInfo(SettingActivity.this.getPackageName(), 0);
                versionName = pi.versionName;

                if (versionName == null || versionName.length() <= 0) {
                    return;
                }
            } catch (Exception e) {
                Log.e("VersionInfo", "Exception", e);
            }
            JSONObject jsonObject;
            try {
                jsonObject = jsonArray.getJSONObject(0);
                String name = jsonObject.getString("name");
                if (!name.equals(versionName)) {
                    new AlertDialog.Builder(SettingActivity.this)
                            .setTitle("版本更新")
                            .setMessage("发现新的版本，点击确定开始下载，下载完成后自动安装")
                            .setNegativeButton("取消", null)
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    update();
                                }
                            })
                            .show();
                } else {
                    new AlertDialog.Builder(SettingActivity.this)
                            .setTitle("版本更新")
                            .setMessage("已是最新版本")
                            .setPositiveButton("关闭", null)
                            .show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            serverHttp.clear();
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_setting);
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
    }

    /**
     * 退出
     *
     * @param v
     */
    public void exit(View v) {
        AlertDialog alertDialog = new AlertDialog.Builder(SettingActivity.this)
                .setTitle("提示:")
                .setMessage("是否退出登录?")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(SettingActivity.this, UserLogin.class);
                        AppManager.finishAllActivity();//结束堆栈中所有的Activity
                        startActivity(intent);
                    }
                })
                .setNegativeButton("取消", null)
                .create(); //创建对话框
        alertDialog.show(); // 显示对话框
    }

    public void checkUpdate(View v){
        serverHttp=new ServerHttp(handler);
        serverHttp.setUrl("Version");
    }
    private void update() {
        Context ctx = SettingActivity.this;
        String url = "http://192.168.1.165:8081/DownLoadAPK";
        if (canDownloadState(ctx)) {
            Log.e("UpdateVersion", "DownloadManager 可用");
            Intent downloadApkIntent = new Intent(ctx, DownApkServer.class);
            Bundle bundle = new Bundle();
            bundle.putString("downloadUrl", url);
            bundle.putString("title", "app-release");
            downloadApkIntent.putExtra("download", bundle);
            ctx.startService(downloadApkIntent);
        } else {
            Log.e("UpdateVersion", "DownloadManager 不可用");
            Intent intent = new Intent();
            intent.setAction("android.intent.action.VIEW");
            Uri content_url = Uri.parse(url);
            intent.setData(content_url);
            ctx.startActivity(intent);
        }

    }

    private static boolean canDownloadState(Context ctx) {
        try {
            int state = ctx.getPackageManager().getApplicationEnabledSetting("com.android.providers.downloads");

            if (state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
